package com.pat.miniloyalty;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class PurchaseServlet extends HttpServlet
{

	/**
	 * Stores information about purchase in DB
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		// Check if user is logged in
		User user = UserServiceFactory.getUserService().getCurrentUser();
		if( user == null )
		{
			resp.sendRedirect("/restricted.jsp?reason=purchase");
		}
		
		// Got User ID from request
		final String uid = req.getParameter("uid");
		// Company ID from request
		final String cid = req.getParameter("cid");
		// Sum of purchase in minor currency
		final String sumStr = req.getParameter("sum");
		
		// TODO: validate purchase data
		
		resp.getWriter().write("Adding " + sumStr + " to UID: " + uid + " (company: " + cid + ")");
		
		int sum = Integer.parseInt(sumStr);
		TranData purchaseData = new TranData(uid, user, sum);
		PersistenceManager pm = LoyaltyPmf.get().getPersistenceManager();
		pm.makePersistent(purchaseData);
		
		resp.sendRedirect("/purchase");
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		resp.setContentType("text/html");
		resp.getWriter().write("Purchase was successfully saved!<br />");
		resp.getWriter().write("<a href='/miniloyalty.jsp'>New purchase</a>");
	}
}
